import { Component } from 'react';
import { getCurrentInstance } from '@tarojs/taro';
import { connect } from 'react-redux'
import { WebView, View } from '@tarojs/components'
import { initCrossDomain } from '@/utils/cross-domain'
import { concatUrl } from '@/utils'

const domain: string = `${BASE_H5_URL}/#`
type State = {
	webUrl: string
  userInfo: any,
}
@connect<any>(({ user }) => ({ user }))
class AppWebView extends Component<any> {
  $instance = getCurrentInstance();
  constructor(props) {
    super(...arguments)
    const { userInfo } = this.props.user
    this.state = {
      webUrl: '',
      userInfo
    }
  }
  state: State

  UNSAFE_componentWillMount() {
    const { url, path, rest, ...other } = this.$instance.router.params
    if (path) {
      console.log(concatUrl(domain + url, { ...other }));
      return this.setState({
        webUrl: concatUrl(domain + url, { ...other })
      })
    }
    if (url) {
      this.setDataConfig()
      // console.log('other: ', concatUrl(url, rest));
      // this.setState({
      //   webUrl: concatUrl(url, rest)
      // })
    }
  }

  setDataConfig() {
    const { userInfo } = this.state
    const { url, rest } = this.$instance.router.params

    let herf = concatUrl(url, rest)
    let data = {}
    if (userInfo.accessId) {
      data = {
        accessId: userInfo.accessId,
        accessKey: userInfo.accessKey,
        userId: userInfo.userId,
        unionid: userInfo.unionid,
        serverTime: userInfo.serverTime
      }
    }
    let webUrl = initCrossDomain({
      url: herf,
      data: data
    })
    this.setState({
      webUrl
    })
  }

  render() {
    const { webUrl } = this.state
    if (!webUrl) return null
    return (
      <View>
        {webUrl && <WebView src={webUrl} />}
      </View>
    )
  }
}
export default AppWebView
